﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;
using DataLayer;
using System.Data;

namespace BusinessLayer
{
    public static class BizRol
    {
        public static dsBoleto retrieveRolesByFilter(String description)
        {
            return DatRol.getRoles(description);
        }

        public static dsBoleto retrieveRoles()
        {
            return retrieveRolesByFilter(string.Empty);
        }



        public static bool removeRol(int idRol)
        {
            List<Util.DBParameter> MisParams = new List<Util.DBParameter>();
            Util.DBParameter MyId = new Util.DBParameter("@IdRol", idRol, System.Data.DbType.Int32);
            Util.DBParameter MyIsActive = new Util.DBParameter("@Habilitado", 0, DbType.Int32);

            MisParams.Add(MyId);
            MisParams.Add(MyIsActive);

            return DatRol.UpdateRol(MisParams);
        }

        public static bool createNewRol(String nombre, List<int> funcionalidades)
        {
            int idNewRol = DatRol.newRol(nombre);
            return DatRol.newRolFuncionalidades(idNewRol, funcionalidades);
        }

        public static bool updateRol(int idRol, String descripcion, List<int> list)
        {
            List<Util.DBParameter> MisParams = new List<Util.DBParameter>();

            Util.DBParameter sSelect = getParameterSubSelect(list, idRol);

            Util.DBParameter pIdRol;
            pIdRol.dbType = System.Data.DbType.Int32;
            pIdRol.value = idRol;
            pIdRol.parameterName = "@IdRol";

            Util.DBParameter pDesc;
            pDesc.dbType = System.Data.DbType.String;
            pDesc.value = descripcion;
            pDesc.parameterName = "@Descripcion";

            MisParams.Add(sSelect);
            MisParams.Add(pIdRol);
            MisParams.Add(pDesc);

            return DatRol.UpdateRol(MisParams);
        }

        private static Util.DBParameter getParameterSubSelect(List<int> list, int idRol)
        {
            StringBuilder sbSelect = new StringBuilder();
            sbSelect.Append("(");
            for (int i = 0; i < list.Count; i++)
            {
                sbSelect.Append("(SELECT ");
                sbSelect.Append(list[i]);
                sbSelect.Append(" IdFuncionalidad, ");
                sbSelect.Append(idRol);
                sbSelect.Append(" IdRol) ");
                if (i != list.Count - 1)
                {
                    sbSelect.Append("UNION ");
                }
            }
            sbSelect.Append(")");
            Util.DBParameter pQuery;
            pQuery.dbType = System.Data.DbType.String;
            pQuery.value = sbSelect.ToString();
            pQuery.parameterName = "@QueryUnions";
            return pQuery;
        }
    }
}
